from multiprocessing import Value
import asyncio
from concurrent.futures import ProcessPoolExecutor

shared_counter: Value


def init(counter: Value):
    global shared_counter
    shared_counter = counter


def increment_value():
    # 获取使用锁的上下文管理
    with shared_counter.get_lock():
        shared_counter.value += 1


async def main():
    for _ in range(100):
        counter = Value('d', 0)
        # 告诉进程池使用每个进程的参数counter执行函数init
        with ProcessPoolExecutor(
                initializer=init,
                initargs=((counter,))
        ) as pool:
            await asyncio.get_running_loop().run_in_executor(pool, increment_value)

            print(counter.value)


if __name__ == '__main__':
    asyncio.run(main())
